﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Handy_WPF.MVVM
{
    /// <summary>
    /// 命令基类
    /// </summary>
    public class BaseCommand : ICommand
    {
        private Func<object, bool> _canExecute;
        private Action<object> _execute;
        public BaseCommand(Action<object> execute, Func<object, bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public BaseCommand(Action<object> execute) : this(execute, null) { }

        public BaseCommand(Func<object, bool> canExecute) : this(null, canExecute) { }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (_canExecute != null) CommandManager.RequerySuggested += value;
            }
            remove
            {
                if (_canExecute != null) CommandManager.RequerySuggested -= value;
            }
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            if (_execute != null && CanExecute(parameter)) _execute(parameter);
        }
    }
}
